<template>
  <div class="profile-view">
    <h1 class="title">我的主页</h1>

    <!-- 用户信息骨架屏 -->
    <div v-if="userLoading" class="user-info skeleton">
      <div class="avatar-container">
        <div class="avatar skeleton-item"></div>
        <div class="edit-avatar skeleton-item"></div>
      </div>
      <div class="user-details">
        <div class="username skeleton-item" style="width: 60%; height: 28px"></div>
        <div class="bio skeleton-item" style="width: 80%; height: 20px; margin-bottom: 20px"></div>
        <div class="stats">
          <div class="stat-item skeleton-item" style="width: 50px; height: 40px"></div>
          <div class="stat-item skeleton-item" style="width: 50px; height: 40px"></div>
          <div class="stat-item skeleton-item" style="width: 50px; height: 40px"></div>
        </div>
      </div>
    </div>

    <!-- 实际用户信息 -->
    <div v-else class="user-info">
      <div class="avatar-container">
        <img :src="getOptimizedImageUrl(user.avatarUrl, 100)" alt="用户头像" class="avatar" />
        <button class="edit-avatar"><EditIcon class="edit-icon" /></button>
      </div>
      <div class="user-details">
        <h2 class="username">{{ user.nickname || '未知用户' }}</h2>
        <p class="bio">{{ user.bio || '这个人很懒，什么都没留下' }}</p>
        <div class="stats">
          <div class="stat-item">
            <span class="stat-value">{{ user.followingCount || 0 }}</span>
            <span class="stat-label">关注</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ user.followersCount || 0 }}</span>
            <span class="stat-label">粉丝</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ user.notesCount || 0 }}</span>
            <span class="stat-label">笔记</span>
          </div>
        </div>
      </div>
    </div>

    <button class="edit-profile-btn" @click="navigateToUserProfile" :disabled="userLoading">编辑资料</button>

    <div class="tab-nav">
      <button
        class="tab-btn"
        :class="{ 'active': activeTab === 'notes' }"
        @click="activeTab = 'notes'"
        :disabled="noteStore.isLoading"
      >笔记</button>
      <button
        class="tab-btn"
        :class="{ 'active': activeTab === 'collections' }"
        @click="activeTab = 'collections'"
        :disabled="collectedNotesLoading"
      >收藏</button>
      <button
        class="tab-btn"
        :class="{ 'active': activeTab === 'likes' }"
        @click="activeTab = 'likes'"
        :disabled="likedNotesLoading"
      >喜欢</button>
    </div>

    <NoteDetailModal
      v-if="showNoteModal"
      :note-id="currentNoteId"
      @close="closeNoteModal"
      @like="handleLike"
      @collect="handleCollect"
    />

    <!-- 笔记 Tab -->
    <div v-if="activeTab === 'notes'" class="notes-tab">
      <div v-if="noteStore.isLoading" class="loading">
        <div class="spinner"></div>
        <p>加载笔记中...</p>
      </div>
      <div v-else-if="noteStore.userNotes?.length" class="notes-grid">
        <NoteCard
          v-for="note in noteStore.userNotes"
          :key="note.id"
          :note="note"
          @like="handleLike(note.id)"
          @collect="handleCollect(note.id)"
          @click="openNoteModal(note.id)"
        />
      </div>
      <div v-else class="empty-state">
        <p>你还没有发布任何笔记</p>
        <button class="publish-btn" @click="navigateToPublish">发布第一条笔记</button>
      </div>
      
      <!-- 加载更多按钮 -->
      <div v-if="pagination.notes.hasMore" class="load-more">
        <button 
          class="load-more-btn" 
          @click="loadMoreNotes"
          :disabled="noteStore.isLoading"
        >
          {{ noteStore.isLoading ? '加载中...' : '加载更多' }}
        </button>
      </div>
    </div>

    <!-- 收藏 Tab -->
    <div v-else-if="activeTab === 'collections'" class="collections-tab">
      <div v-if="collectedNotesLoading" class="loading">
        <div class="spinner"></div>
        <p>加载收藏笔记中...</p>
      </div>
      <div v-else-if="collectedNotes.length" class="notes-grid">
        <NoteCard
          v-for="note in collectedNotes"
          :key="note.id"
          :note="note"
          @like="handleLike(note.id)"
          @collect="handleCollect(note.id)"
          @click="openNoteModal(note.id)"
        />
      </div>
      <div v-else class="empty-state">
        <p>你还没有收藏任何笔记</p>
      </div>
      
      <!-- 加载更多按钮 -->
      <div v-if="pagination.collections.hasMore" class="load-more">
        <button 
          class="load-more-btn" 
          @click="loadMoreCollections"
          :disabled="collectedNotesLoading"
        >
          {{ collectedNotesLoading ? '加载中...' : '加载更多' }}
        </button>
      </div>
    </div>

    <!-- 喜欢 Tab -->
    <div v-else-if="activeTab === 'likes'" class="likes-tab">
      <div v-if="likedNotesLoading" class="loading">
        <div class="spinner"></div>
        <p>加载点赞笔记中...</p>
      </div>
      <div v-else-if="likedNotes.length" class="notes-grid">
        <NoteCard
          v-for="note in likedNotes"
          :key="note.id"
          :note="note"
          @like="handleLike(note.id)"
          @collect="handleCollect(note.id)"
          @click="openNoteModal(note.id)"
        />
      </div>
      <div v-else class="empty-state">
        <p>你还没有点赞任何笔记</p>
      </div>
      
      <!-- 加载更多按钮 -->
      <div v-if="pagination.likes.hasMore" class="load-more">
        <button 
          class="load-more-btn" 
          @click="loadMoreLikes"
          :disabled="likedNotesLoading"
        >
          {{ likedNotesLoading ? '加载中...' : '加载更多' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { EditIcon } from 'lucide-vue-next'
import NoteCard from '@/components/common/NoteCard.vue'
import NoteDetailModal from '@/components/common/NoteDetailModal.vue'
import { useAuthStore } from '@/store/auth'
import { useNoteStore } from '@/store/notes'
import { useLikeStore } from '@/store/likes'
import { useCollectionStore } from '@/store/collections'
import { 
  getUserNotesWithStats, 
  getCollectedNotesWithStats, 
  getLikedNotesWithStats 
} from '@/api/notes'

const router = useRouter()
const authStore = useAuthStore()
const noteStore = useNoteStore()
const likeStore = useLikeStore()
const collectionStore = useCollectionStore()

const activeTab = ref('notes')
const likedNotes = ref([])
const collectedNotes = ref([])
const likedNotesLoading = ref(false)
const collectedNotesLoading = ref(false)
const showNoteModal = ref(false)
const currentNoteId = ref(null)
const userLoading = ref(true)

// 分页配置
const pagination = ref({
  notes: { page: 1, pageSize: 10, hasMore: true },
  collections: { page: 1, pageSize: 10, hasMore: true },
  likes: { page: 1, pageSize: 10, hasMore: true }
})

/* 用户信息 */
const user = computed(() => {
  const u = authStore.user || {}
  return {
    username: u.username || '',
    nickname: u.nickname || '未知用户',
    avatarUrl: u.avatarUrl || u.avatar || '',
    bio: u.bio || '这个人很懒，什么都没留下',
    followingCount: u.followingCount || 0,
    followersCount: u.followersCount || 0,
    notesCount: u.notesCount || 0
  }
})

/* 导航 */
const navigateToUserProfile = () => router.push({ name: 'UserProfile', params: { id: authStore.user.id } })
const navigateToPublish = () => router.push('/publish')

/* 生命周期 */
onMounted(async () => {
  if (!authStore.isAuthenticated) {
    alert('请先登录')
    router.push('/login')
    return
  }
  userLoading.value = false
  await loadUserNotes()
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

/* Tab 切换：按需加载 */
watch(activeTab, async (val) => {
  if (val === 'collections' && !collectedNotes.value.length) await loadUserCollections()
  if (val === 'likes' && !likedNotes.value.length) await loadUserLikes()
})

/* 滚动加载 */
const handleScroll = () => {
  const nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 500
  if (nearBottom) {
    switch(activeTab.value) {
      case 'notes': 
        if (pagination.value.notes.hasMore && !noteStore.isLoading) loadMoreNotes()
        break
      case 'collections':
        if (pagination.value.collections.hasMore && !collectedNotesLoading.value) loadMoreCollections()
        break
      case 'likes':
        if (pagination.value.likes.hasMore && !likedNotesLoading.value) loadMoreLikes()
        break
    }
  }
}

/* 数据转换函数（修复字段匹配问题） */
function supplementNoteFields(note) {
  return {
    ...note,
    id: note.id || 'unknown-note',
    title: note.title || '无标题',
    content: note.content || '',
    // 修复：使用后端返回的 coverImageUrl
    coverImage: note.coverImageUrl || 'https://picsum.photos/id/1/800/400',
    likes: Number(note.likes ?? 0),
    collects: Number(note.collects ?? 0),
    comments: Number(note.comments ?? 0),
    isLiked: Boolean(note.isLiked ?? false),
    isCollected: Boolean(note.isCollected ?? false),
    // 修复：使用后端返回的 userId 和 nickname
    user: {
      id: note.userId || 'unknown-user',
      name: note.nickname || '匿名用户',
      avatar: note.avatarUrl || 'https://picsum.photos/id/64/100/100'
    },
    createdAt: note.createdAt || new Date().toISOString(),
    updatedAt: note.updatedAt || new Date().toISOString()
  }
}

/* 加载函数（修复API响应处理） */
async function loadUserNotes() {
  try {
    // 重置分页
    pagination.value.notes.page = 1
    pagination.value.notes.hasMore = true
    
    noteStore.isLoading = true
    const response = await getUserNotesWithStats(
      authStore.user.id,
      pagination.value.notes.page,
      pagination.value.notes.pageSize
    )
    
    // 修复：正确处理API响应结构
    if (response && response.code === 200 && Array.isArray(response.data)) {
      noteStore.userNotes = response.data.map(supplementNoteFields)
    } else {
      noteStore.userNotes = []
    }
    
    // 检查是否还有更多数据
    if (noteStore.userNotes.length < pagination.value.notes.page * pagination.value.notes.pageSize) {
      pagination.value.notes.hasMore = false
    } else {
      pagination.value.notes.page++
    }
  } catch (e) {
    console.error('加载用户笔记失败', e)
  } finally {
    noteStore.isLoading = false
  }
}

async function loadMoreNotes() {
  try {
    noteStore.isLoading = true
    const response = await getUserNotesWithStats(
      authStore.user.id, 
      pagination.value.notes.page, 
      pagination.value.notes.pageSize
    )
    
    // 修复：正确处理API响应结构
    if (response && response.code === 200 && Array.isArray(response.data)) {
      const moreNotes = response.data.map(supplementNoteFields)
      noteStore.userNotes = [...noteStore.userNotes, ...moreNotes]
    }
    
    // 检查是否还有更多数据
    if (response.data.length < pagination.value.notes.pageSize) {
      pagination.value.notes.hasMore = false
    } else {
      pagination.value.notes.page++
    }
  } catch (e) {
    console.error('加载更多笔记失败', e)
  } finally {
    noteStore.isLoading = false
  }
}

async function loadUserCollections() {
  collectedNotesLoading.value = true
  try {
    // 重置分页
    pagination.value.collections.page = 1
    pagination.value.collections.hasMore = true
    
    const response = await getCollectedNotesWithStats(
      authStore.user.id,
      pagination.value.collections.page,
      pagination.value.collections.pageSize
    )
    
    // 修复：正确处理API响应结构
    if (response && response.code === 200 && Array.isArray(response.data)) {
      collectedNotes.value = response.data.map(supplementNoteFields)
    } else {
      collectedNotes.value = []
    }
    
    // 检查是否还有更多数据
    if (collectedNotes.value.length < pagination.value.collections.page * pagination.value.collections.pageSize) {
      pagination.value.collections.hasMore = false
    } else {
      pagination.value.collections.page++
    }
  } catch (e) {
    console.error('加载收藏失败', e)
  } finally {
    collectedNotesLoading.value = false
  }
}

async function loadMoreCollections() {
  collectedNotesLoading.value = true
  try {
    const response = await getCollectedNotesWithStats(
      authStore.user.id,
      pagination.value.collections.page,
      pagination.value.collections.pageSize
    )
    
    // 修复：正确处理API响应结构
    if (response && response.code === 200 && Array.isArray(response.data)) {
      const moreNotes = response.data.map(supplementNoteFields)
      collectedNotes.value = [...collectedNotes.value, ...moreNotes]
    }
    
    // 检查是否还有更多数据
    if (response.data.length < pagination.value.collections.pageSize) {
      pagination.value.collections.hasMore = false
    } else {
      pagination.value.collections.page++
    }
  } catch (e) {
    console.error('加载更多收藏失败', e)
  } finally {
    collectedNotesLoading.value = false
  }
}

async function loadUserLikes() {
  likedNotesLoading.value = true
  try {
    // 重置分页
    pagination.value.likes.page = 1
    pagination.value.likes.hasMore = true
    
    const response = await getLikedNotesWithStats(
      authStore.user.id,
      pagination.value.likes.page,
      pagination.value.likes.pageSize
    )
    
    // 修复：正确处理API响应结构
    if (response && response.code === 200 && Array.isArray(response.data)) {
      likedNotes.value = response.data.map(supplementNoteFields)
    } else {
      likedNotes.value = []
    }
    
    // 检查是否还有更多数据
    if (likedNotes.value.length < pagination.value.likes.page * pagination.value.likes.pageSize) {
      pagination.value.likes.hasMore = false
    } else {
      pagination.value.likes.page++
    }
  } catch (e) {
    console.error('加载点赞失败', e)
  } finally {
    likedNotesLoading.value = false
  }
}

async function loadMoreLikes() {
  likedNotesLoading.value = true
  try {
    const response = await getLikedNotesWithStats(
      authStore.user.id,
      pagination.value.likes.page,
      pagination.value.likes.pageSize
    )
    
    // 修复：正确处理API响应结构
    if (response && response.code === 200 && Array.isArray(response.data)) {
      const moreNotes = response.data.map(supplementNoteFields)
      likedNotes.value = [...likedNotes.value, ...moreNotes]
    }
    
    // 检查是否还有更多数据
    if (response.data.length < pagination.value.likes.pageSize) {
      pagination.value.likes.hasMore = false
    } else {
      pagination.value.likes.page++
    }
  } catch (e) {
    console.error('加载更多点赞失败', e)
  } finally {
    likedNotesLoading.value = false
  }
}

/* 弹窗 & 事件 */
const openNoteModal = id => { currentNoteId.value = id; showNoteModal.value = true }
const closeNoteModal = () => { showNoteModal.value = false }

const handleLike = async noteId => {
  const note = findNote(noteId)
  if (!note) return
  const ok = note.isLiked
    ? await likeStore.unlikeNote(authStore.user.id, noteId)
    : await likeStore.likeNote(authStore.user.id, noteId)
  if (ok) {
    note.isLiked = !note.isLiked
    note.likes += note.isLiked ? 1 : -1
    if (activeTab.value === 'likes' && !note.isLiked) likedNotes.value = likedNotes.value.filter(n => n.id !== noteId)
  }
}

const handleCollect = async noteId => {
  const note = findNote(noteId)
  if (!note) return
  const ok = note.isCollected
    ? await collectionStore.uncollectNote(authStore.user.id, noteId)
    : await collectionStore.collectNote(authStore.user.id, noteId)
  if (ok) {
    note.isCollected = !note.isCollected
    note.collects += note.isCollected ? 1 : -1
    if (activeTab.value === 'collections' && !note.isCollected) collectedNotes.value = collectedNotes.value.filter(n => n.id !== noteId)
  }
}

function findNote(noteId) {
  return likedNotes.value.find(n => n.id === noteId) ||
         collectedNotes.value.find(n => n.id === noteId) ||
         noteStore.userNotes.find(n => n.id === noteId) ||
         noteStore.multipleNotes[noteId]
}

// 优化图片加载函数
const getOptimizedImageUrl = (url, size = 100) => {
  if (!url) return `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/${size}/${size}`
  
  if (url.startsWith('http')) {
    // 添加图片优化参数
    return `${url}?x-oss-process=image/resize,w_${size}/quality,q_80`
  }
  
  return `https://${url}?x-oss-process=image/resize,w_${size}/quality,q_80`
}
</script>

<style scoped>
.profile-view {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 24px;
  text-align: center;
  color: #333;
}

.user-info {
  display: flex;
  padding: 24px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  align-items: center;
}

.avatar-container {
  position: relative;
  margin-right: 24px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  object-fit: cover;
  border: 2px solid #f5f5f5;
}

.edit-avatar {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-color: var(--color-primary);
  border: 2px solid white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.edit-avatar:hover {
  background-color: #3d43b1;
}

.edit-icon {
  width: 16px;
  height: 16px;
  color: white;
}

.user-details {
  flex: 1;
}

.username {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 8px 0;
  color: #333;
}

.bio {
  font-size: 16px;
  color: #666;
  margin: 0 0 16px 0;
  line-height: 1.5;
}

.stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #888;
}

.edit-profile-btn {
  width: 100%;
  padding: 12px;
  background-color: white;
  border: 1px solid var(--color-primary);
  border-radius: 8px;
  color: var(--color-primary);
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  margin-bottom: 24px;
  transition: all 0.3s;
}

.edit-profile-btn:hover {
  background-color: #f5f7ff;
}

.tab-nav {
  display: flex;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.tab-btn {
  flex: 1;
  padding: 16px;
  background: none;
  border: none;
  font-size: 16px;
  font-weight: bold;
  color: #666;
  cursor: pointer;
  position: relative;
  transition: color 0.3s;
}

.tab-btn.active {
  color: var(--color-primary);
}

.tab-btn.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3px;
  background-color: var(--color-primary);
}

.tab-btn:hover:not(.active):not(:disabled) {
  color: #444;
}

.tab-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.notes-tab,
.collections-tab,
.likes-tab {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 24px;
}

.loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 32px 0;
  color: #888;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(78, 84, 200, 0.3);
  border-radius: 50%;
  border-top-color: var(--color-primary);
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 32px 0;
  color: #888;
}

.publish-btn, .btn-primary {
  margin-top: 16px;
  padding: 10px 24px;
  background-color: var(--color-primary);
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.publish-btn:hover, .btn-primary:hover {
  background-color: #3d43b1;
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.load-more-btn {
  padding: 10px 24px;
  background-color: #f5f7ff;
  color: var(--color-primary);
  border: 1px solid var(--color-primary);
  border-radius: 24px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.load-more-btn:hover {
  background-color: var(--color-primary);
  color: white;
}

.load-more-btn:disabled {
  background-color: #f0f0f0;
  color: #aaa;
  cursor: not-allowed;
  border-color: #ddd;
}

/* 骨架屏动画 */
.skeleton {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.skeleton-item {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  border-radius: 4px;
}

@keyframes loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

@media (max-width: 768px) {
  .notes-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }
  
  .user-info {
    flex-direction: column;
    text-align: center;
  }
  
  .avatar-container {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .stats {
    justify-content: center;
  }
}
</style>